package com.lingjtx.im.core.common;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Slf4j
@Configuration
public class NettyServer {

    private final WebSocketChannelInitializer webSocketChannelInitializer;

    public NettyServer(WebSocketChannelInitializer webSocketChannelInitializer) {
        this.webSocketChannelInitializer = webSocketChannelInitializer;
    }

    @Value("${netty.port}")
    private int port;

    @Bean(destroyMethod = "shutdownGracefully")
    public EventLoopGroup bossGroup() {
        return new NioEventLoopGroup(1); // boss线程可单线程
    }

    @Bean(destroyMethod = "shutdownGracefully")
    public EventLoopGroup workerGroup() {
        return new NioEventLoopGroup(); // 默认CPU*2线程数
    }

    @Bean
    public ApplicationRunner start(EventLoopGroup bossGroup, EventLoopGroup workerGroup) {
        return _ -> {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(webSocketChannelInitializer)
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true);

            bootstrap.bind(port).addListener((ChannelFutureListener) future -> {
                if (future.isSuccess()) {
                    log.info("✅ WebSocket Netty Server started on port: {}", port);
                } else {
                    log.error("❌ WebSocket Netty Server failed to start", future.cause());
                }
            });
        };
    }
}

